#!/usr/bin/env python

class Formatter(object):
    """Formatter class.
    
    Helper class to format data into human readable form.
    """
    
    @staticmethod
    def byte(value, precision=2):
        """Format number into byte format.
        
        Args:
            value: A number.
            precision: An integer represent desired precision.
            
        Returns:
            A string repesent a value in byte, kB, MB, TB or PB.
            
        Examples:
            >>> Formatter.byte(1)
            '1 byte'
            >>> Formatter.byte(1024)
            '1.0 kB'
            >>> Formatter.byte(1024*1234, 2)
            '1.21 MB'
        """
        
        abbrevs = (
            (1<<50L, 'PB'),
            (1<<40L, 'TB'),
            (1<<30L, 'GB'),
            (1<<20L, 'MB'),
            (1<<10L, 'kB'),
            (1, 'bytes')
        )
        if value == 1:
            return '1 byte'
        for factor, suffix in abbrevs:
            if value >= factor: break
        return '%.*f %s' % (precision, value / (factor * 1.0), suffix)
    
    @staticmethod
    def version(version):
        """Format version number into human readable form.
        
        Args:
            version: A string representation of version in
                major.minor.release.revision format. eg: 1.0.0.0
        
        Returns:
            A human readable version.
        """
        
        versions = version.split('.')
        stages = ('Alpha', 'Beta', 'Release Candidate', 'Public Release')
        if int(versions[2]) == 3:
            if int(versions[3]) == 0:
                r = '%s.%s' % (versions[0], versions[1])
            else:
                t = (versions[0], versions[1], versions[3])
                r = '%s.%s Revision %s' % t
        else:
            if int(versions[3]) == 0:
                r = '%s.%s %s' % (versions[0], versions[1],
                                  stages[int(versions[2])])
            else:
                r = '%s.%s %s %s' % (versions[0], versions[1],
                                     stages[int(versions[2])], versions[3])
        return r
    
if __name__ == '__main__':
    try:
        print Formatter.byte(12453535, 2)
    except:
        import traceback
        
        print traceback.format_exc()
